<template>
  <div class='searchSeggest' @click="$emit('isSearchSuggsetShow', false)">
    <van-cell-group inset>
      <!-- 当搜索框为空或报错时显示‘搜索’提示 -->
      <van-cell
        v-if="isSearchTip"
      >
        <div slot="title">搜索{{searchText}}</div>
      </van-cell>
      <!-- / 当搜索框为空或报错时显示‘搜索’提示 -->

      <!-- 搜索联想词列表 -->
      <van-cell
        v-for="(item, index) of searchSongList"
        :key="index"
        @click="handlerSearchSong(item)"
      >
        <div
          slot="title"
          v-html="highlightKeyWords(item)"
        ></div>
      </van-cell>
      <!-- / 搜索联想词列表 -->
    </van-cell-group>
  </div>
</template>

<script>
import { Cell, CellGroup } from 'vant'
import { getSearchSuggset } from '@/api/music'

export default {
  name: 'searchSeggest',
  components: {
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup
  },
  props: {
    searchText: {
      required: false,
      type: String
    }
  },
  data () {
    return {
      preventJitter: null, // 定时器
      searchSongList: [],
      isSearchTip: false
    }
  },
  computed: {},
  watch: {
    // 监控 searchText 的变化，去请求搜索建议
    searchText: {
      handler: function () {
        const _that = this
        // 关键字每次改变后，间隔一定时间，再发送请求
        if (this.searchText.trim() === '') {
          return
        }
        clearTimeout(this.preventJitter)
        this.preventJitter = setTimeout(async function () {
          try {
            const { data } = await getSearchSuggset({
              keywords: _that.searchText
            })
            _that.searchSongList = new Array(...data.result.allMatch)
            _that.isSearchTip = false
          } catch (error) {
            _that.isSearchTip = true
          }
        }, 500)
      },
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    // 高亮显示搜索建议内的关键字
    highlightKeyWords (item) {
      return item.keyword.replace(
        new RegExp(this.searchText, 'gi'),
        `<span style="color: red">${this.searchText}</span>`
      )
    },
    handlerSearchSong (songName) {
      this.$emit('onSearchSongs', songName.keyword)
    }
  }
}
</script>
<style lang='less' scoped>
.searchSeggest {
  position: absolute;
  top: 60px;
  z-index: 10;
  width: 100%;
  height: 100vh;
  /deep/ .van-cell-group--inset {
    box-shadow: 0px 10px 10px rgb(216, 216, 216);
  }
}
</style>
